﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security;
using System.Text.RegularExpressions;

class CountAndSortWords
{
    static void Main()
    {
        try
        {
            using (StreamReader input = new StreamReader("input.txt"))
            {
                using (StreamWriter output = new StreamWriter("output.txt"))
                {
                    string text;
                    string word;

                    Dictionary<string, int> listOfWords = new Dictionary<string, int>();

                    text = input.ReadToEnd();

                    using (StreamReader words = new StreamReader("words.txt"))
                    {
                        while ((word = words.ReadLine()) != null)
                        {
                            int count = Regex.Matches(text, word).Count;

                            listOfWords.Add(word, count);
                        }
                    }
                    var ordered = listOfWords.OrderBy(x => x.Value).ToDictionary(x => x.Key, x => x.Value);

                    foreach (KeyValuePair<string, int> pair in ordered)
                    {
                        output.WriteLine(pair.Key);                        
                    }
                }
            }
        }
        catch (FileNotFoundException)
        {
            Console.WriteLine("Cannot find file");
        }
        catch (DirectoryNotFoundException)
        {
            Console.WriteLine("Invalid Folder ");
        }
        catch (PathTooLongException)
        {
            Console.WriteLine("The path is too long");
        }
        catch (UnauthorizedAccessException)
        {
            Console.WriteLine("You don`t have access!");
        }
        catch (NotSupportedException)
        {
            Console.WriteLine("Cannot open this file!");
        }
        catch (SecurityException)
        {
            Console.WriteLine("Not enough permission to open file!");
        }
    }
}